package com.khalil.kkadmin.infrastructure.web;

import cn.dev33.satoken.filter.SaTokenContextFilterForJakartaServlet;
import com.khalil.kkadmin.infrastructure.web.security.LoginCheckInterceptor;
import jakarta.servlet.DispatcherType;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.EnumSet;

@Configuration
public class CustomisedWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginCheckInterceptor());
    }

    /**
     * 解决sse请求中出现错误：SaTokenContext 上下文尚未初始化
     * <a href="https://gitee.com/dromara/sa-token/issues/IC4XFE">...</a>
     */
    @Bean
    public FilterRegistrationBean saTokenContextFilterForJakartaServlet() {
        FilterRegistrationBean bean = new FilterRegistrationBean<>(new SaTokenContextFilterForJakartaServlet());
        // 配置 Filter 拦截的 URL 模式
        bean.addUrlPatterns("/*");
        // 设置 Filter 的执行顺序,数值越小越先执行
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        bean.setAsyncSupported(true);
        bean.setDispatcherTypes(EnumSet.of(DispatcherType.ASYNC, DispatcherType.REQUEST));
        return bean;
    }
}
